package com.saas.dao.impl;

import com.saas.dao.IStudentDao;
import com.saas.entity.Student;
import com.saas.util.DruidUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class StudentDaoImpl implements IStudentDao{

    private QueryRunner qr = new QueryRunner(DruidUtil.getDataSource());
    @Override
    public List<Student> getAllStudents() {
        try {
            return qr.query("select * from stu", new BeanListHandler<Student>(Student.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int saveStudent(Student student) {
        try {
            return qr.update("insert into stu values(?, ?, ?)", student.getStu_name(), student.getStu_sex(), student.getC_id());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int updateStudent(Student student) {
        try {
            return qr.update("update stu set stu_name = ?, stu_sex = ?, c_id = ? where id = ?", student.getStu_name(), student.getStu_sex(), student.getC_id(), student.getStu_id());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int deleteStudentById(int id) {
        try {
            return qr.update("delete from stu where stu_id = ?", id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
